import React from 'react';
import PropTypes from 'prop-types';
import {hot} from 'react-hot-loader';

import {Route, Switch} from '@folio/stripes/core';
import {CommandList, HasCommand} from '@folio/stripes/components';

// eslint-disable-next-line import/no-unresolved
import * as Routes from './routes';

import pkg from '../package';
import commands from './commands';

import {BASE_PAHT} from './constants';

class BookInStorageRouting extends React.Component {
  static propTypes = {
    stripes: PropTypes.shape({
      hasPerm: PropTypes.func.isRequired,
    }).isRequired,
    location: PropTypes.object.isRequired,
    match: PropTypes.object.isRequired,
    history: PropTypes.object,
  }

  static actionNames = ['stripesHome'];

  constructor(props) {
    super(props);
    this.props.stripes.setLocale('zh-CN');
  }

  componentDidMount() {
  }

  noMatch() {
    const {
      location: { pathname },
    } = this.props;

    return (
      <div>
        <h2>
          路径错误
        </h2>
        <p>
          路径{pathname}不存在！
        </p>
      </div>
    );
  }

  focusSearchField = () => {
    const { history } = this.props;
    const el = document.getElementById('input-user-search');
    if (el) {
      el.focus();
    } else {
      history.push(pkg.stripes.home);
    }
  }

  shortcuts = [
    {
      name: 'search',
      handler: this.focusSearchField
    },
  ];

  checkScope = () => {
    return document.body.contains(document.activeElement);
  }

  render() {
    const {
      match: { path },
      stripes
    } = this.props;

    this.shortcutScope = document.body;
    const base = BASE_PAHT;

    return (
      <CommandList commands={commands}>
        <HasCommand
          commands={this.shortcuts}
          isWithinScope={this.checkScope}
          scope={this.shortcutScope}
        >
          <Switch>
            <Route path={`${base}/create`} component={Routes.BookInStorageEditContainer} />
            <Route path={`${base}/:id/edit`} component={Routes.BookInStorageEditContainer} />
            <Route path={`${base}/view/:id`} component={Routes.BookInStorageDetailFullscreenContainer} />
            <Route path={base} component={Routes.BookInStorageSearchContainer}>
              <Route path={`${base}/preview/:id`} component={Routes.BookInStorageDetailContainer} />
            </Route>
            <Route render={this.noMatch} />
          </Switch>
        </HasCommand>
      </CommandList>
    );
  }
}

export default hot(module)(BookInStorageRouting);
